package com.app.medicalcontrol.fragment.Robot.child;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.app.medicalcontrol.R;
import com.app.medicalcontrol.basis.BasisFragment;
import com.app.medicalcontrol.basis.Constants;
import com.app.medicalcontrol.bean.BasisBean;
import com.app.medicalcontrol.bean.Robot;
import com.app.medicalcontrol.event.RobotStatusRefreshEvent;
import com.app.medicalcontrol.fragment.Robot.child.item.IJSetFragment;
import com.app.medicalcontrol.fragment.Robot.child.item.RobotStatusFragment;
import com.app.medicalcontrol.fragment.WebViewX5Fragment;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.suke.widget.SwitchButton;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

/**
 * Created by otis on 2018/4/11.
 */

public class RobotItemFragment extends BasisFragment implements RadioGroup.OnCheckedChangeListener{

    private DialogFragment dialog;
    public static  int robotId;
    private RadioGroup mRadioGroup;
    private FrameLayout mLayout;
    private FragmentManager fragmentManager;
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";
    private Fragment currentFragment = new Fragment();
    private List<Fragment> fragments = new ArrayList<>();
    private int currentIndex = 0;

    @BindView(R.id.tv_robot_name)
    public TextView robotName;
    @BindView(R.id.sb_open_close)
    public SwitchButton robotStatusBtn;
    @BindView(R.id.ll_reset_robot_name)
    public LinearLayout mLlSetRobotName;

    public static RobotItemFragment newInstance(int robotId) {
        RobotItemFragment fragment = new RobotItemFragment();
        fragment.robotId = robotId;
        return fragment;
    }


    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_robot_item);
        setTitle(getString(R.string.robot_status));
        mRadioGroup= (RadioGroup) findViewById(R.id.rg_radio_navigation);
        mRadioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        fragmentManager = getChildFragmentManager();
        getList(savedInstanceState);
        robotStatusBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                openOrClose(isChecked);
            }
        });
        mLlSetRobotName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetRobotName();
            }
        });
    }

    private void initFragment(Bundle savedInstanceState){
        if (savedInstanceState != null) { // “内存重启”时调用
            //获取“内存重启”时保存的索引下标
            currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT,0);
            //注意，添加顺序要跟下面添加的顺序一样！！！！
            fragments.removeAll(fragments);
            fragments.add(fragmentManager.findFragmentByTag(0+""));
            fragments.add(fragmentManager.findFragmentByTag(1+""));
            fragments.add(fragmentManager.findFragmentByTag(2+""));
            //恢复fragment页面
            restoreFragment();
        }else{      //正常启动时调用
            fragments.add(RobotStatusFragment.newInstance());
            fragments.add(new IJSetFragment());
            fragments.add(WebViewX5Fragment.getInstance(Constants.H5_PLAY+"?robot_id="+robotId,getString(R.string.playback_set),true));
            showFragment();
        }
    }

    private void getList(final Bundle savedInstanceState) {
        showProgress();
        RequestParams params = new RequestParams();
        params.put("robot_id",robotId);
        HttpRestClient.get(Constants.URL_ROBOT_INFO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        Robot bean = (Robot) result;
                        robotName.setText(bean.getName());
                        robotStatusBtn.setChecked(bean.checkFromInt(bean.getStart_status()));
                        initFragment(savedInstanceState);
                    }
                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, Robot.class);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(CURRENT_FRAGMENT,currentIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.rb_first:
                currentIndex = 0;
                break;
            case R.id.rb_second:
                currentIndex = 1;
                break;
            case R.id.rb_third:
                currentIndex = 2;
                break;
        }
        showFragment();
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment(){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //如果之前没有添加过
        if(!fragments.get(currentIndex).isAdded()){
            int a = currentIndex;
            transaction
                    .hide(currentFragment)
                    .add(R.id.fl_radio_show,fragments.get(currentIndex),""+currentIndex);  //第三个参数为添加当前的fragment时绑定一个tag
        }else{
            transaction
                    .hide(currentFragment)
                    .show(fragments.get(currentIndex));
        }
        currentFragment = fragments.get(currentIndex);
        transaction.commit();
    }

    /**
     * 恢复fragment
     */
    private void restoreFragment(){
        FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if(i == currentIndex){
                mBeginTreansaction.show(fragments.get(i));
            }else{
                mBeginTreansaction.hide(fragments.get(i));
            }
        }
        mBeginTreansaction.commit();
        //把当前显示的fragment记录下来
        currentFragment = fragments.get(currentIndex);
    }

    @OnClick(R.id.back_btn)
    public void toBack(){
            pop();
    }

    public void openOrClose(boolean checked){
        showProgress();
        RequestParams params = new RequestParams();
        params.put("robot_id",robotId);
        params.put("status",checked);
        HttpRestClient.get(Constants.URL_UPSWITCH, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, Robot.class);
    }

    public void resetRobotName(){
       dialog = new CircleDialog.Builder()
                .setCanceledOnTouchOutside(false)
                .setCancelable(true)
                .setInputManualClose(true)
                .setTitle("输入框")
                .setInputHint(""+robotName.getText().toString().trim())
                .autoInputShowKeyboard()
                .setInputCounter(20)
                .setNegative("取消", null)
                .setPositiveInput("确定", (text, v) -> {
                    if (TextUtils.isEmpty(text)) {
                        dialog.dismiss();
                    } else {
                        resetRobotNameHttp(text);
                        dialog.dismiss();
                    }
                })
               .setWidth(0.7f)
                .show(getChildFragmentManager());
    }

    private void resetRobotNameHttp(String name){
        showProgress();
        RequestParams params = new RequestParams();
        params.put("robot_id",robotId);
        params.put("name",name);
        HttpRestClient.get(Constants.URL_UP_NAME, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        showToast("修改成功");
                        robotName.setText(name);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, BasisBean.class);
    }


    @OnClick(R.id.rb_first)
    public void clickFirstBtn(){
        EventBus.getDefault().post(new RobotStatusRefreshEvent("刷新界面"));
    }
}
